package com.example.chapter06.database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.chapter06.entity.LoginInfo;

public class LoginDBHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "login.db";
    private static final String TABLE_NAME = "login_info";
    private static final int DB_VERSION = 1;
    private static LoginDBHelper mHelper = null;
    private SQLiteDatabase mRDB = null; // 读数据库
    private SQLiteDatabase mWDB = null; // 写数据库

    public LoginDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    // 利用单例模式获取数据库帮助器的唯一实例
    public static LoginDBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new LoginDBHelper(context);
        }
        return mHelper;
    }

    // 打开数据库的读连接
    public SQLiteDatabase openReadLink() {
        if (mRDB == null || !mRDB.isOpen()) {
            mRDB = mHelper.getReadableDatabase();
        }
        return mRDB;
    }

    // 打开数据库的写连接
    public SQLiteDatabase openWriteLink() {
        if (mWDB == null || !mWDB.isOpen()) {
            mWDB = mHelper.getWritableDatabase();
        }
        return mWDB;
    }

    // 关闭数据库连接
    public void closeLink() {
        if (mRDB != null && mRDB.isOpen()) {
            mRDB.close();
            mRDB = null;
        }

        if (mWDB != null && mWDB.isOpen()) {
            mWDB.close();
            mWDB = null;
        }
    }

    // 创建数据库，执行建表语句
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table if not exists " + TABLE_NAME + " (" +
                "  _id integer primary key autoincrement not null," +
                "  phone varchar not null," +
                "  password varchar not null," +
                "  remember INTEGER NOT NULL);";
        db.execSQL(sql);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void save(LoginInfo info) {
        // 如果数据库中已经存在该手机号，先删除，再添加
        try {
            mWDB.beginTransaction();
            delete(info);
            insert(info);
            mWDB.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mWDB.endTransaction();
        }
    }

    public void delete(LoginInfo info) {
        // 删除数据库中的指定手机号的记录
        mWDB.delete(TABLE_NAME, "phone=?", new String[]{info.phone});
    }

    public long insert(LoginInfo info) {
        ContentValues values = new ContentValues();
        values.put("phone", info.phone);
        values.put("password", info.password);
        values.put("remember", info.remember);
        int ret = 1;
        try {
            mWDB.beginTransaction();
            mWDB.insert(TABLE_NAME, null, values);
            mWDB.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
            ret = -1;
        } finally {
            mWDB.endTransaction();
        }
        return ret;
    }


    @SuppressLint("Range")
    public LoginInfo queryTop() {
        LoginInfo info = null;
        String sql = "select * from " + TABLE_NAME + " where remember=1 order by _id desc limit 1";
        Cursor cursor = mRDB.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            info = new LoginInfo();
            info.id = cursor.getInt(cursor.getColumnIndex("_id"));
            info.phone = cursor.getString(cursor.getColumnIndex("phone"));
            info.password = cursor.getString(cursor.getColumnIndex("password"));
            info.remember = cursor.getInt(cursor.getColumnIndex("remember")) == 1;
        }
        return info;
    }


    @SuppressLint("Range")
    public LoginInfo queryByPhone(String phone) {
        LoginInfo info = null;
        String sql = "select * from " + TABLE_NAME + " where phone=? and remember=1";
        Cursor cursor = mRDB.rawQuery(sql, new String[]{phone});
        while (cursor.moveToNext()) {
            info = new LoginInfo();
            info.id = cursor.getInt(cursor.getColumnIndex("_id"));
            info.phone = cursor.getString(cursor.getColumnIndex("phone"));
            info.password = cursor.getString(cursor.getColumnIndex("password"));
            info.remember = cursor.getInt(cursor.getColumnIndex("remember")) == 1;
        }
        return info;
    }
}
